package com.gamenew.bluetoothdemo.ui.fragment;


import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.audiofx.Visualizer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.gamenew.bluetoothdemo.R;
import com.gamenew.bluetoothdemo.adapter.CommonAdapter;
import com.gamenew.bluetoothdemo.adapter.ViewHolder;
import com.gamenew.bluetoothdemo.bean.EventBusBean;
import com.gamenew.bluetoothdemo.bean.EventBusVpBean;
import com.gamenew.bluetoothdemo.bean.EventBusWrite;
import com.gamenew.bluetoothdemo.bean.MusicBean;
import com.gamenew.bluetoothdemo.data.GattAttributes;
import com.gamenew.bluetoothdemo.i.ICountDownCallBack;
import com.gamenew.bluetoothdemo.i.IEventTag;
import com.gamenew.bluetoothdemo.utils.IntelligentUtils;
import com.gamenew.bluetoothdemo.utils.MusicFilter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class MusicModeFragment extends BaseFragment implements MediaPlayer.OnPreparedListener,
        MediaPlayer.OnVideoSizeChangedListener, MediaPlayer.OnCompletionListener {
    private static final int CAPTURESIZE = 128;
    @BindView(R.id.last_music)
    ImageView lastMusic;
    @BindView(R.id.pause)
    ImageView pause;
    @BindView(R.id.next_music)
    ImageView nextMusic;
    @BindView(R.id.music_random)
    ImageView musicRandom;
    private String TAG = MusicModeFragment.class.getSimpleName();

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.img_go)
    ImageView imgGo;
    @BindView(R.id.voice_progress)
    SeekBar voiceProgress;
    @BindView(R.id.img_1)
    ImageView img1;
    @BindView(R.id.img_2)
    ImageView img2;
    @BindView(R.id.img_3)
    ImageView img3;
    @BindView(R.id.img_4)
    ImageView img4;
    @BindView(R.id.lv_music)
    ListView lvMusic;
    @BindView(R.id.inner_music)
    View innerMusic;
    @BindView(R.id.outer_music)
    View outerMusic;
    @BindView(R.id.music_progres)
    SeekBar musicProgres;
    @BindView(R.id.btn_random)
    View btnRandom;
    @BindView(R.id.btn_recycle)
    View btnRecycle;
    @BindView(R.id.music_recycle)
    View music_recycle;
    @BindView(R.id.ll_bg)
    LinearLayout ll_bg;
    private int currentMusic = 0;
    private boolean isRecycle = true;//是否循环播放
    private boolean isInner = true;//是否播放内置的歌曲
    private List<MusicBean> innerList = new ArrayList<>();
    private List<MusicBean> outerList = new ArrayList<>();
    private List<MusicBean> musicList = new ArrayList<>();
    private CommonAdapter<MusicBean> musicAdapter;
    private MediaPlayer mediaPlayer;
    private AudioManager systemService;
    private Visualizer visualizer;
    private byte[] bytes;
    private Timer timer;
    private String tag = "";//用于记录是音乐到massage
    private byte[] fftmodel;
    private int fft;
    //能量等级
    private static int LEVELSTEP = 0;
    //频率等级
    private static int POWERLEVEL = 20;
    private static int MAXLEVEL = 13;
    private byte[] mData = new byte[POWERLEVEL];
    private static boolean first = true;
    public MusicFilter musicFilter;

    public MusicModeFragment() {
        // Required empty public constructor
        EventBus.getDefault().register(this);
    }

    @Override
    protected int setViewId() {
        return R.layout.fragment_music_mode;
    }

    @Override
    protected void findViews(View view) {
        ButterKnife.bind(this, view);
        titleText.setText(R.string.titlebar_music);
        imgBack.setVisibility(View.VISIBLE);
        ll_bg.setBackground(new BitmapDrawable(IntelligentUtils.readBitMap(getContext(), R.drawable.beijing)));
    }

    @Override
    protected void initEvent() {
        musicProgres.setOnSeekBarChangeListener(seekBarChangeListener);
        voiceProgress.setOnSeekBarChangeListener(voiceSeek);
    }

    static final int SAMPLE_RATE_IN_HZ = 8000;
    static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ,
            AudioFormat.CHANNEL_IN_DEFAULT, AudioFormat.ENCODING_PCM_16BIT);
    AudioRecord mAudioRecord;

    @Override
    protected void init() {
        mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                SAMPLE_RATE_IN_HZ, AudioFormat.CHANNEL_IN_DEFAULT,
                AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE);


        systemService = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
        int streamMaxVolume = systemService.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        voiceProgress.setMax(streamMaxVolume);
        int streamVolume = systemService.getStreamVolume(AudioManager.STREAM_MUSIC);
        voiceProgress.setProgress(streamVolume);
        innerList.clear();
//        MusicBean musicBean = new MusicBean();
//        musicBean.setId(R.raw.music);
//        musicBean.setInner(true);
//        Uri uri = Uri.parse("android.resource://" + getActivity().getPackageName() + "/" + R.raw.music);
//        musicBean.setMusicname("music1");
//        musicBean.setUri(uri);
//        innerList.add(musicBean);
        initAdapter();


//        timerSchedule();
    }

    int test = 30;

    private void timerSchedule() {
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        if (bytes != null) {
                            int v = (int) ((Math.abs(bytes[64]) * ((80 * 1.0) / 128)));
//                            if(v >= 80){
//                                v = 80;
//                            }
//                            test++;
//                            if(test > 250){
//                                test = 0;
//                            }
//                            int v = (int) ((Math.abs(mData[10]) * ((80 * 1.0) / 128)));
//                        Log.e(TAG,bytes[64]+"sss");
//                        Log.e(TAG, "写入数据 bytes：" + (GattAttributes.MUSIC_HEAD + toHx(255 - v) + toHx(v)).toUpperCase());
//                            EventBus.getDefault().post(new EventBusWrite((GattAttributes.MUSIC_HEAD +toHx(255 - v) + toHx(v)).toUpperCase()));
//                            Log.e(TAG, "写入数据 bytes：" + (GattAttributes.MUSIC_HEAD + toHx(255 - v) + toHx(v)).toUpperCase());
                            EventBus.getDefault().post(new EventBusWrite((GattAttributes.MUSIC_HEAD + toHx(255 - v) + toHx(v)).toUpperCase()));

                        }
                    }
                }
            }, 0, 220);
        }
    }

    public String toHx(int v) {
        String hv = Integer.toHexString(v);
        if (hv.length() < 2) {
            return "0" + hv;
        }
        return hv;
    }

    private void initAdapter() {
        if (musicAdapter == null)
            musicAdapter = new CommonAdapter<MusicBean>(getContext(), R.layout.item_music, musicList) {
                @Override
                public void convert(ViewHolder holder, final MusicBean musicBean, final int position, final int currentposition) {
                    holder.setText(R.id.tv_music_name, musicBean.getMusicname());
                    if (first == true && position == 0) {
                        holder.setBackGround(R.id.item_music, Color.alpha(255));
                        holder.setBackGround(R.id.item_music, Color.parseColor("#9933CC"));
                        ScrollToCurrentMusic(position);
                    } else if (first == true && position != 0) {
                        holder.setBackGround(R.id.item_music, Color.alpha(0));
                    } else if (first != true) {
                        if (position != currentposition) {
                            holder.setBackGround(R.id.item_music, Color.alpha(0));
                        } else {
                            holder.setBackGround(R.id.item_music, Color.parseColor("#9933CC"));
                        }
                    }
                    holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            timerSchedule();
                            if (currentMusic != position) {
                                musicAdapter.NotifyChange(position);
                            }
                            playMusic(musicBean);
                            currentMusic = position;
                            pause.setImageResource(R.drawable.yinyuezhanting);
                            musicAdapter.notifyDataSetChanged();
                            first = false;
                        }
                    });

                }
            };

        lvMusic.setAdapter(musicAdapter);
    }


    //播放
    private void playMusic(MusicBean musicBean) {
        if (musicBean.isInner()) {
            Log.e("Inner", "if");
            isInner = true;
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.reset();
                mediaPlayer.release();
                mediaPlayer = null;
            }
            mediaPlayer = MediaPlayer.create(getActivity(), (int) musicBean.getId());
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnCompletionListener(this);
        } else {
            Log.e("Inner", "else");
            isInner = false;
            long id = musicBean.getId();
            Uri contentUri = ContentUris.withAppendedId(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.reset();
//                mediaPlayer.release();
//                mediaPlayer = null;
                EventBus.getDefault().post(id);
            }
            if (mediaPlayer == null) {
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setOnPreparedListener(this);
                mediaPlayer.setOnCompletionListener(this);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            }

            initVisualer();
            try {
                mediaPlayer.setDataSource(getActivity(), contentUri);
                mediaPlayer.prepareAsync();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }


    private void initVisualer() {
//        if (visualizer != null) {
//            visualizer.release();
//            visualizer = null;
//        }
        if (visualizer == null) {
            visualizer = new Visualizer(mediaPlayer.getAudioSessionId());
            Log.e("media", "" + mediaPlayer.getAudioSessionId());
            LEVELSTEP = 128 / MAXLEVEL;
            visualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
            Log.e("CaptureSizeRange", Visualizer.getCaptureSizeRange()[0] + "");
        }
        visualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {

            @Override
            public void onWaveFormDataCapture(Visualizer visualizer,
                                              byte[] waveform, int samplingRate) {
//                    Log.e(TAG, waveform.length + "长度");
//                Log.e(TAG+"bytes", waveform[25] + "");
                bytes = waveform;

            }

            @Override
            public void onFftDataCapture(Visualizer visualizer, byte[] fft,
                                         int samplingRate) {
                byte[] model = new byte[fft.length / 2 + 1];
                model[0] = (byte) Math.abs(fft[1]);
                int j = 1;
                for (int i = 2; i < fft.length; ) {
                    model[j] = (byte) Math.hypot(fft[i], fft[i + 1]);
                    i += 2;
                    j++;
                }

                for (int i = 0; i < fft.length; i++) {
                    Log.e("model" + i, "" + fft[i]);
                }

                for (int i = 0; i < POWERLEVEL; i++) {
                    final byte a = (byte) (Math.abs(model[POWERLEVEL - i]) / LEVELSTEP);
                    byte b = mData[i];

                    if (a > b) {
                        mData[i] = a;
                    } else {
                        if (b > 0) {
                            mData[i]--;
                        }
                    }
                }
                Log.e("fft", "here");

            }
        }, Visualizer.getMaxCaptureRate() / 2, true, false);

//            visualizer.setCaptureSize(CAPTURESIZE);
        visualizer.setEnabled(true);

    }

    //加载手机上的歌曲数据
    @Override
    protected void loadData() {
        outerList.clear();
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    1);
        }
        ContentResolver contentResolver = getActivity().getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = contentResolver.query(uri, null, null, null, null);
        if (cursor == null) {
            // query failed, handle error.
        } else if (!cursor.moveToFirst()) {
            // no media on the device
        } else {
            int titleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
            int type = cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE);
            do {
                long thisId = cursor.getLong(idColumn);
                String thisTitle = cursor.getString(titleColumn);
                String thistype = cursor.getString(type).trim();
                Log.e(TAG, "id: " + thisId + "  thisTile: " + thisTitle + " type:" + thistype);
                if (thistype.equals("audio/ext-mpeg") || thistype.equals("audio/x-wav") || thistype.equals("audio/mpeg")) {
                    MusicBean musicBean = new MusicBean();
                    musicBean.setMusicname(thisTitle);
                    musicBean.setId(thisId);
                    musicBean.setInner(false);
                    outerList.add(musicBean);
                }
                // ...process entry...
            } while (cursor.moveToNext());
        }
        musicList.clear();
        musicList.addAll(outerList);
        musicAdapter.notifyDataSetChanged();
        cursor.close();
    }


    @OnClick({R.id.img_back, R.id.img_go, R.id.inner_music, R.id.outer_music, R.id.btn_random, R.id.btn_recycle, R.id.last_music, R.id.music_recycle, R.id.pause, R.id.next_music, R.id.music_random, R.id.img_go_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                getActivity().finish();
                break;
            case R.id.img_go_left:
                EventBus.getDefault().post(new EventBusBean(IEventTag.MUSICTOMASSAGE));
                EventBus.getDefault().post(new EventBusWrite(GattAttributes.MASSAGE_MODE_1));
                break;
            case R.id.img_go:
                break;
            case R.id.inner_music:
//                musicList.clear();
//                musicList.addAll(STRENGTH_MODE_1);
//                musicAdapter.notifyDataSetChanged();
                break;
            case R.id.outer_music:
                musicList.clear();
                musicList.addAll(outerList);
                musicAdapter.notifyDataSetChanged();
                break;
            case R.id.music_random:
            case R.id.btn_random:
                btnRandom.setBackgroundResource(R.drawable.xunhuanbg1);
                btnRecycle.setBackgroundResource(R.drawable.xunhanbg);
                isRecycle = false;
                break;
            case R.id.music_recycle:
            case R.id.btn_recycle:
                btnRandom.setBackgroundResource(R.drawable.xunhanbg);
                btnRecycle.setBackgroundResource(R.drawable.xunhuanbg1);
                isRecycle = true;
                break;
            case R.id.last_music:
                lastMusicGo();
                break;
            case R.id.pause:
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    EventBus.getDefault().post(new EventBusWrite(GattAttributes.MUSICPAUSE));
//                    EventBus.getDefault().post(new EventBusWrite("A7FF00"));
                    pause.setImageResource(R.drawable.yinyuekaishi);
                } else if (mediaPlayer != null) {
                    timerSchedule();
                    mediaPlayer.start();
                    pause.setImageResource(R.drawable.yinyuezhanting);
                } else {
                    if (outerList.size() > 0) {
                        timerSchedule();
                        playMusic(outerList.get(0));
                        pause.setImageResource(R.drawable.yinyuezhanting);
                    }
                }
                break;
            case R.id.next_music:
                nextMusicGo();
                break;
        }
    }

    private void lastMusicGo() {
        int size = outerList.size();
        int preMusic = currentMusic;
        if (isRecycle) {
            if (size > 0) {
                int temp = currentMusic - 1;
                if (temp < 0) {
                    currentMusic = (temp + size) % size;
                } else {
                    currentMusic = temp % size;
                }
                changeMusicColor(currentMusic, preMusic);
                playMusic(outerList.get(currentMusic));
                pause.setImageResource(R.drawable.yinyuezhanting);
            }
        } else {
            if (size > 0) {
                int random = (int) (Math.random() * size);
                changeMusicColor(random, preMusic);
                playMusic(outerList.get(random));
                pause.setImageResource(R.drawable.yinyuezhanting);
            }
        }
    }

    private void nextMusicGo() {
        int size = outerList.size();
        if (isRecycle) {
            if (size > 0) {
                int premusic = currentMusic;
                currentMusic = (currentMusic + 1) % size;
                changeMusicColor(currentMusic, premusic);
                playMusic(outerList.get(currentMusic));
                pause.setImageResource(R.drawable.yinyuezhanting);
            }
        } else {
            if (size > 0) {
                int premusic = currentMusic;
                currentMusic = (int) (Math.random() * size);
                changeMusicColor(currentMusic, premusic);
                playMusic(outerList.get(currentMusic));
                pause.setImageResource(R.drawable.yinyuezhanting);
            }
        }

    }

    /*
    * Created by 余均宇2016/11/16*/
    public void changeMusicColor(int position, int preposition) {
        Log.e("currentMp", "" + position);
        if (position != preposition) {
            musicAdapter.NotifyChange(position);
            ScrollToCurrentMusic(position);
            musicAdapter.notifyDataSetChanged();
            first = false;
        }

        currentMusic = position;
    }

    /*
    * Created by 余均宇2016/11/16*/
    public void ScrollToCurrentMusic(int position) {
        lvMusic.smoothScrollToPosition(position);
    }


    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
//        EventBus.getDefault().post(mediaPlayer);
        mediaPlayer.start();
        setMusicProgress(mediaPlayer);
    }

    @Override
    public void onVideoSizeChanged(MediaPlayer mediaPlayer, int i, int i1) {

    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
//        Log.e(TAG,"播完一曲！");
        nextMusicGo();
    }

    private void setMusicProgress(final MediaPlayer mediaPlayer) {
        musicProgres.setMax(mediaPlayer.getDuration());
        IntelligentUtils.getInstance().countDownTime((long) mediaPlayer.getDuration(), new ICountDownCallBack() {
            @Override
            public void onCountDown(Long currentTime) {
                try {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        if (mediaPlayer.getCurrentPosition() != -1) {
                            musicProgres.setProgress(mediaPlayer.getCurrentPosition());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCompleteDown() {

            }
        });
    }

    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
//            setMusicProgress(i);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (mediaPlayer != null && mediaPlayer.isPlaying())
                mediaPlayer.seekTo(seekBar.getProgress());
        }
    };

    private void setMusicProgress(int progress) {
        if (mediaPlayer != null) {
            mediaPlayer.seekTo(progress);
        }
    }

    SeekBar.OnSeekBarChangeListener voiceSeek = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            systemService.setStreamVolume(AudioManager.STREAM_MUSIC, seekBar.getProgress(), 0);

        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy");
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (mediaPlayer != null) {
//            if (mediaPlayer.isPlaying()) {
//                mediaPlayer.pause();
//                mediaPlayer.stop();
//                mediaPlayer.reset();
//                mediaPlayer.release();
//                mediaPlayer=null;
//            }
            mediaPlayer.release();
        }
        if (visualizer != null) {
            visualizer.release();
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
//            if (mediaPlayer != null) {
//                mediaPlayer.stop();
//                mediaPlayer.reset();
//                mediaPlayer.release();
//                mediaPlayer = null;
//            }
//            if (visualizer != null) {
//                visualizer.release();
//            }
//            EventBus.getDefault().post(new EventBusWrite(GattAttributes.MUSICSSTOP));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void currentPosition(EventBusVpBean event) {
        Log.e(TAG, event.functionTag + "");

        switch (event.functionTag) {
            case 0:
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }

                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.release();
                    mediaPlayer = null;
                    EventBus.getDefault().post(new EventBusWrite(GattAttributes.MUSICPAUSE));
                    EventBus.getDefault().post(new EventBusWrite(GattAttributes.MUSICSSTOP));
                    pause.setImageResource(R.drawable.yinyuekaishi);
                }
                if (visualizer != null) {
                    visualizer.setEnabled(false);
                    visualizer.release();
                    visualizer = null;
                }
                break;
        }
    }

    public void isFirst() {
        first = true;
        musicAdapter.notifyDataSetChanged();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


}
